package com.shopx.base.utils;


import com.shopx.base.constants.ResultCodeEnum;
import com.shopx.base.exception.ShopxException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@Slf4j
public class WordExportUtil {

  private Configuration configuration = null;

  //构造函数生成实例并设置编码
  public WordExportUtil() {
    configuration = new Configuration();
    configuration.setDefaultEncoding("utf-8");
  }


  /**
   * 导出word文档，导出到本地
   *
   * @param tempName，要使用的模板
   * @param dataMap，模板中变量数据
   * @param outFile，输出文档路径
   */
  public boolean exportDoc(String tempName, Map<?, ?> dataMap, File outFile, String templatePath) throws Exception {
    boolean status = false;
    configuration.setDirectoryForTemplateLoading(new File(templatePath));
    Template t = null;
    Writer out = null;
    try {
      t = configuration.getTemplate(tempName);
      t.setEncoding("utf-8");
      out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));

      status = true;
      t.process(dataMap, out);
    } catch (Exception e) {
      log.error("exportDoc.error.", e);
      throw new ShopxException(ResultCodeEnum.DOWNLOAD_ERROR);
    } finally {
      if (out != null) {
        out.close();
      }
    }
    return status;
  }

  /**
   * 导出下载
   *
   * @param tempName：模板名称
   * @param docName：导出文件名称
   * @param dataMap：参数
   * @param templatePath：模板存放路径（配置）
   * @param resp：响应
   * @return
   * @throws Exception
   */
  public boolean exportDoc(String tempName, String docName, Map<?, ?> dataMap, String templatePath, HttpServletResponse resp) throws Exception {
    boolean status = false;
    ServletOutputStream sos = null;
    InputStream fin = null;
    Writer out = null;
    File outFile = null;
    Template t = null;
    if (resp != null) {
      resp.reset();
    }
    configuration.setDirectoryForTemplateLoading(new File(templatePath));
    try {
      t = configuration.getTemplate(tempName);
      t.setEncoding("utf-8");
      String name = "temp" + (int) (Math.random() * 100000) + ".doc";
      outFile = new File(name);
      out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
      status = true;
      t.process(dataMap, out);
      fin = new FileInputStream(outFile);
      // 文档下载
      resp.setCharacterEncoding("utf-8");
      resp.setContentType("application/msword");
      docName = new String(docName.getBytes("UTF-8"), "ISO-8859-1");
      resp.setHeader("Content-disposition", "attachment;filename=" + docName + ".doc");
      sos = resp.getOutputStream();
      byte[] buffer = new byte[512]; // 缓冲区
      int bytesToRead = -1;
      while ((bytesToRead = fin.read(buffer)) != -1) {
        sos.write(buffer, 0, bytesToRead);
      }
    } catch (IOException e) {
      log.error("exportDoc.error.", e);
      throw new ShopxException(ResultCodeEnum.DOWNLOAD_ERROR);
    } finally {
      if (fin != null) {
        try {
          fin.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (sos != null) {
        try {
          sos.flush();
          sos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (out != null) {
        out.flush();
        out.close();
      }
      if (outFile != null) {
        outFile.delete(); // 删除临时文件
      }
    }
    return status;
  }
}

